package org.ttitfly.ttcore.service.account;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.AntUrlPathMatcher;
import org.springframework.security.web.util.UrlMatcher;
import org.springframework.transaction.annotation.Transactional;
import org.ttitfly.ttcore.entity.account.Resource;
import org.ttitfly.ttcore.entity.account.Role;
@Transactional(readOnly = true)
public class SSFilterInvocationSecurityMetadataSource implements
		FilterInvocationSecurityMetadataSource {
	
	private AccountManager accountManager;

	@javax.annotation.Resource(name="accountManager")
	public void setAccountManager(AccountManager accountManager) {
		this.accountManager = accountManager;
	}

	private UrlMatcher urlMatcher = new AntUrlPathMatcher();

	private static Map<String, List<ConfigAttribute>> map;

	public SSFilterInvocationSecurityMetadataSource() {
//		System.out.println(accountManager);
	}
	
	
	@Transactional(readOnly = true)
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		map = new HashMap<String, List<ConfigAttribute>>();
		List<Resource> resources = accountManager.getAllResources();
		
		for (Resource resource : resources) {
			// 资源所拥有的角色列表
			List<ConfigAttribute> list = new ArrayList<ConfigAttribute>();
			List<Role> roles = resource.getRoles();
			for (Role role : roles) {
				ConfigAttribute configAttribute = new SecurityConfig(role
						.getName());
				list.add(configAttribute);
			}
			map.put(resource.getUrl(), list);
		}
		return null;
	}

	public Collection<ConfigAttribute> getAttributes(Object arg0)
			throws IllegalArgumentException {
		String accessURL = ((FilterInvocation) arg0).getRequestUrl();
		Iterator<String> iter = map.keySet().iterator();
		while (iter.hasNext()) {
			String url = iter.next(); // 获得每一个被保护的资源
			if (this.urlMatcher.pathMatchesUrl(accessURL, url)) {
				return map.get(url);
			}
		}

		return null;
	}

	public boolean supports(Class<?> arg0) {
		return true;
	}
	
	
}
